<?php

/**
 * Description of RepoTerapeuta
 *
 * @author  Mariano Renkine
 * @author  Fernando Arau
 */
class RepoTerapeuta extends Repositorio
{

  function __construct()
  {
    $this->tabla = "terapeuta";
    $this->id = "idTerapeuta";
  }

  function agregar(Terapeuta $terapeuta)
  {
    try
    {

      $link = $this->OpenDB();
      $this->beginTransaction();
      $query = "INSERT INTO " . $this->tabla . "(nombre, apellido, nroDocumento, domicilio, telefono, email, cuit, tipoDocumento, usuario, deshabilitado, esExterno) values (";
      $query .= "'" . $terapeuta->getNombre() . "', ";
      $query .= "'" . $terapeuta->getApellido() . "', ";
      $query .= "'" . $terapeuta->getNroDocumento() . "', ";
      $query .= "'" . $terapeuta->getDomicilio() . "',";
      $query .= "'" . $terapeuta->getTelefono() . "',";
      $query .= "'" . $terapeuta->getEmail() . "',";
      $query .= "'" . $terapeuta->getCuit() . "', ";
      $query .= $terapeuta->getIdTipoDocumento() . ",";
      $query .= "'" . $terapeuta->getUsuario() . "',";
      $query .= $terapeuta->getDeshabilitado() . ", ";
      $query .= $terapeuta->getEsExterno() . ")";
      $result = $this->PostSQL($query);
      $id = $this->GetInsertedId();
      if ($result && is_array($terapeuta->getTratamientos()))
      {
        /* @var $tratamiento Tratamiento */
        foreach ($terapeuta->getTratamientos() as $tratamiento)
        {
          if ($result)
          {
            $query = "INSERT INTO terapeuta_tratamiento (tratamiento, terapeuta) VALUES (";
            $query .= $tratamiento->getId() . ", ";
            $query .= $id . ")";
            $result = $this->PostSQL($query);
          }
        }
      }
      if ($result)
      {
        $this->commitTransaction();
      } else
      {
        $this->rollbackTransaction();
      }
      $this->CloseDB($link);
      return $result;
    } catch (Exception $ex)
    {
      return $ex;
    }
  }

  function modificar(Terapeuta $terapeuta)
  {
    try
    {
      $link = $this->OpenDB();
      $this->beginTransaction();
      if ($this->VerificarVersion($terapeuta->getVersion(), $terapeuta->getId()))
      {
        $query = "UPDATE " . $this->tabla . " SET ";
        $query .= "nombre = '" . $terapeuta->getNombre() . "', ";
        $query .= "apellido = '" . $terapeuta->getApellido() . "', ";
        $query .= "nroDocumento = '" . $terapeuta->getNroDocumento() . "', ";
        $query .= "cuit = '" . $terapeuta->getCuit() . "', ";
        $query .= "domicilio = '" . $terapeuta->getDomicilio() . "', ";
        $query .= "telefono = '" . $terapeuta->getTelefono() . "', ";
        $query .= "email = '" . $terapeuta->getEmail() . "', ";
        $query .= "tipoDocumento = " . $terapeuta->getIdTipoDocumento() . ", ";
        $query .= "usuario = '" . $terapeuta->getUsuario() . "', ";
        $query .= "deshabilitado = " . $terapeuta->getDeshabilitado() . ", ";
        $query .= "esExterno = " . $terapeuta->getEsExterno();
        $query .= " WHERE " . $this->id . " = " . $terapeuta->getId();
        $result = $this->PostSQL($query);
        if ($result)
        {
          $query = $this->setContext($terapeuta->getUsuario());
          $query .= "DELETE FROM terapeuta_tratamiento WHERE terapeuta = " . $terapeuta->getId();
          $result = $this->PostSQL($query);
          if ($result && is_array($terapeuta->getTratamientos()))
          {
            /* @var $tratamiento Tratamiento */
            foreach ($terapeuta->getTratamientos() as $tratamiento)
            {
              if ($result)
              {
                $query = "INSERT INTO terapeuta_tratamiento (tratamiento, terapeuta, usuario) VALUES (";
                $query .= $tratamiento->getId() . ", ";
                $query .= $terapeuta->getId() . ",";
                $query .= "'" . $terapeuta->getUsuario() . "')";
                $result = $this->PostSQL($query);
              }
            }
          }
          if ($result)
          {
            $this->commitTransaction();
            $this->CloseDB($link);
            return $result;
          }
        }
      } else
      {
        $this->rollbackTransaction();
        $this->CloseDB($link);
        throw new Exception("El registro ha sido modificado por otro usuario", ERROR_VERSION);
      }
    } catch (Exception $ex)
    {
      return $ex->getCode() + "|" + $ex->getMessage();
    }
  }

  function buscar($id)
  {
    $link = $this->OpenDB();
    $queryTxt = "SELECT nombre, apellido, nroDocumento, domicilio, telefono, 
      email, cuit, tipoDocumento, deshabilitado, esExterno, convert(BIGINT, version) AS version 
      FROM terapeuta where idTerapeuta = " . $id;
    $query = $this->GetSQL($queryTxt);

    $terapeuta = new Terapeuta();
    $terapeuta->setEsExterno($query[0]->esExterno);
    $terapeuta->setVersion($query[0]->version);
    $terapeuta->setApellido($query[0]->apellido);
    $terapeuta->setCuit($query[0]->cuit);
    //$terapeuta->setDeshabilitado($query[0]->deshabilitado);
    $terapeuta->setDomicilio($query[0]->domicilio);
    $terapeuta->setEmail($query[0]->email);
    $terapeuta->setNombre($query[0]->nombre);
    $terapeuta->setNroDocumento($query[0]->nroDocumento);
    $terapeuta->setTelefono($query[0]->telefono);
    $repoTipoDocumento = new RepoTipoDocumento();
    $terapeuta->setTipoDocumento($repoTipoDocumento->buscar($query[0]->tipoDocumento));
    $terapeuta->setId($id);
    $query = "SELECT tratamiento, nombre FROM terapeuta_tratamiento JOIN tratamiento ON tratamiento = idTratamiento ";
    $query .= "WHERE terapeuta = " . $id;
    $tratamientosObj = $this->GetSQL($query);
    if (is_array($tratamientosObj))
    {
      foreach ($tratamientosObj as $tratamientoObj)
      {
        $tratamiento = new Tratamiento();
        $tratamiento->setId($tratamientoObj->tratamiento);
        $tratamiento->setNombre($tratamientoObj->nombre);
        $tratamientos[] = $tratamiento;
      }
      $terapeuta->setTratamientos($tratamientos);
    }
    $this->CloseDB($link);
    return $terapeuta;
  }

  function listar()
  {
    $link = $this->OpenDB();
    $terapeutasObj = parent::listar();
    $this->CloseDB($link);
    $terapeutas = "";
    foreach ($terapeutasObj as $terapeutaObj)
    {
      $terapeuta = new Terapeuta();
      $terapeuta->setApellido($terapeutaObj->apellido);
      $terapeuta->setCuit($terapeutaObj->cuit);
      $terapeuta->setEsExterno($terapeutaObj->esExterno);
      $terapeuta->setDeshabilitado($terapeutaObj->deshabilitado);
      $terapeuta->setDomicilio($terapeutaObj->domicilio);
      $terapeuta->setEmail($terapeutaObj->email);
      $terapeuta->setNombre($terapeutaObj->nombre);
      $terapeuta->setNroDocumento($terapeutaObj->nroDocumento);
      $terapeuta->setTelefono($terapeutaObj->telefono);
      $repoTipoDocumento = new RepoTipoDocumento();
      $terapeuta->setTipoDocumento($repoTipoDocumento->buscar($terapeutaObj->tipoDocumento));
      $terapeuta->setId($terapeutaObj->idTerapeuta);
      $terapeuta->setVersion($terapeutaObj->version);
      $terapeutas[] = $terapeuta;
    }
    return $terapeutas;
  }

  function valiarDisponibilidadTerapeuta($terapeuta, $fecha, $hora)
  {
    $link = $this->OpenDB();
    $where = "terapeuta = " . $terapeuta . " AND fecha = '" . $this->SqlDate($fecha) . "' AND 
      ((desde1 <= " . $hora . " AND hasta1 >= " . ((int)$hora +1) . ") OR 
        (desde2 <= " . $hora . " AND hasta2 >= " . ((int)$hora +1) . "))";
//    $horariosTerapeuta = $this->GetTableDataByWhere('horario_terapeuta', $where);    
    $queryTerapeuta = "SELECT terapeuta FROM horario_terapeuta WHERE " . $where;
    $horariosTerapeuta = $this->GetSQL($queryTerapeuta);
    if ($horariosTerapeuta != false)
    {
      $whereReserva = "fechaReserva = '" . $this->SqlDate($fecha) . " $hora:00:00' AND terapeuta = '" . $terapeuta . "'";
      //$queryReserva = $this->GetTableDataByWhere('reserva', $whereReserva);
//      $query = "SELECT idReserva, tratamiento, terapeuta, gabinete, usuario, usuarioModificacion, 
//      cliente, comprobante, estado, CONVERT(VARCHAR(10), fechaReserva,120) AS fechaReserva, 
//      CONVERT(VARCHAR(8), fechaReserva,108) AS horaReserva, fechaCreacion, horaCreacion, 
//      numeroHabitacion FROM RESERVA WHERE ".$whereReserva;

      $query = "SELECT 1 FROM reserva WHERE " . $whereReserva;
      $queryReserva = $this->GetSQL($query);
      return ($queryReserva != false) ? 0 : 1;
    } else
    {
      return 0;
    }

    /**
     * @todo Ver por qué se puso el siguiente return.
     */
    return $horariosTerapeuta;
    $this->CloseDB($link);
  }

  function valiarDisponibilidadTerapeutaSinReservaActual($terapeuta, $fecha, $hora, $reserva)
  {
    $link = $this->OpenDB();
    $where = "terapeuta = " . $terapeuta . " AND fecha = '" . $this->SqlDate($fecha) . "' AND 
      ((desde1 <= " . $hora . " AND hasta1 >= " . ((int)$hora +1) . ") OR 
        (desde2 <= " . $hora . " AND hasta2 >= " . ((int)$hora +1) . "))";
    
    $horariosTerapeuta = $this->GetTableDataByWhere('horario_terapeuta', $where);    
    if ($horariosTerapeuta != false)
    {
      $whereReserva = "fechaReserva = '" . $this->SqlDate($fecha) . " $hora:00:00' AND terapeuta = '" . $terapeuta . "' AND idReserva <> " . $reserva;
      $queryReserva = $this->GetTableDataByWhere('reserva', $whereReserva);
      if ($queryReserva != false)
      {
        return 0;
      }
//      else
//      {
//        return 1;
//      }
    } else
    {
      return 0;
    }
    return $horariosTerapeuta;
    $this->CloseDB($link);
  }

  function eliminar($id)
  {
    $link = $this->OpenDB();
    $this->beginTransaction();
    $eliminar = "DELETE FROM terapeuta_tratamiento WHERE terapeuta = " . $id;
    $result = $this->PostSQL($eliminar);
    if ($result)
    {
      $result = parent::eliminar($id);
    }
    if ($result)
    {
      $this->commitTransaction();
    } else
    {
      $this->rollbackTransaction();
    }
    $this->CloseDB($link);
    return $result;
  }

}

?>
